import React from "react";
import { AgGridReact } from "ag-grid-react";
import PropTypes from "prop-types";
import { ModuleRegistry, AllCommunityModule, themeQuartz } from "ag-grid-community";
import { mergeProps } from "src/utils/index";
import Btns from "./btns";

ModuleRegistry.registerModules([AllCommunityModule]);

const theme = themeQuartz.withParams({
    wrapperBorder: true,
    rowBorder: true,
    headerRowBorder: true,
    columnBorder: true,
});

const defaultProps = {
    grandTotalRow: "bottom",
    height: 600,
};

const Table = p => {
    const props = mergeProps(defaultProps, p);
    const { dataSource, columns, enableCellSpan, btns, height, pinnedBottomRowData } = props;
    return (
        <div className="grid-table" style={{ height: `${height}px` }}>
            {btns && <Btns btns={btns} position="left" />}
            <AgGridReact
                rowData={dataSource}
                columnDefs={columns}
                enableCellSpan={enableCellSpan}
                suppressMovableColumns={true}
                theme={theme}
                stopEditingWhenCellsLoseFocus={true}
                pinnedBottomRowData={pinnedBottomRowData}
            />
        </div>
    );
};

Table.propTypes = {
    dataSource: PropTypes.array,
    columns: PropTypes.array,
    enableCellSpan: PropTypes.bool,
    grandTotalRow: PropTypes.oneOf(["bottom", "top"]),
    btns: PropTypes.arrayOf(
        PropTypes.shape({
            label: PropTypes.string,
            key: PropTypes.string.isRequired,
            fn: PropTypes.func,
            hidden: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
        }),
    ),
    height: PropTypes.number,
    pinnedBottomRowData: PropTypes.arrayOf(PropTypes.object),
};

export default Table;
